package com.licheedev.testdemo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.licheedev.myutils.LogPlus
import com.licheedev.myutils.SystemUtil
import com.licheedev.screenpower.RootScreenPower
import com.licheedev.silentinstall.ApkInfo
import com.licheedev.silentinstall.SilentInstall
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File


class MainActivity : AppCompatActivity() {


    private lateinit var rootScreenPower: RootScreenPower

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        LogPlus.e("taskId=${taskId}")

        setContentView(R.layout.activity_main)

        tvVersion.setText("当前版本\n${SystemUtil.getVersionName(this)}(${SystemUtil.getVersionCode(this)})")


        rootScreenPower = RootScreenPower(this)

        btnOffThemOn.setOnClickListener {
            offThenOn()
        }

        btnInstall.setOnClickListener {
            install()
        }

        btnStartSecondActivity.setOnClickListener {
            startActivity(Intent(this, SecondActivity::class.java))
        }
        
        registerScreenReceiver()


    }

    /** 息屏，5秒后亮屏 */
    private fun offThenOn() {
        GlobalScope.launch(Dispatchers.IO) {
            rootScreenPower.screenOff()
            LogPlus.e("息屏")
            delay(5000)
            LogPlus.e("亮屏")
            rootScreenPower.screenOn()
        }
    }

    private fun install() {

        GlobalScope.launch(Dispatchers.IO) {

            val dir = application.getExternalFilesDir("apks")
            dir?.mkdirs()
            val file = File(dir, "ver999_9.9.9_debug.apk")
            Log.i("ApkInfo", ApkInfo(file).toString()) // 打印apk文件信息

            SilentInstall.install(file) // 执行安装，需要在子线程中执行
        }
    }

    fun registerScreenReceiver() {
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_SCREEN_ON)
        filter.addAction(Intent.ACTION_SCREEN_OFF)
        mScreenReceiver = ScreenReceiver()
        registerReceiver(mScreenReceiver, filter)
    }

    private lateinit var mScreenReceiver: ScreenReceiver

    class ScreenReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {

            when (intent.action) {
                Intent.ACTION_SCREEN_OFF -> {
                    LogPlus.e("息屏了")
                }
                Intent.ACTION_SCREEN_ON -> {
                    LogPlus.e("亮屏了")
                }
            }
        }
    }


}